package com.greate.community.controller;

import com.greate.community.entity.Comment;
import com.greate.community.entity.DiscussPost;
import com.greate.community.entity.Event;
import com.greate.community.entity.Permission;
import com.greate.community.event.EventProducer;
import com.greate.community.service.CommentService;
import com.greate.community.service.DiscussPostService;
import com.greate.community.service.master.RBACService;
import com.greate.community.service.master.SectionForbidService;
import com.greate.community.util.CommunityConstant;
import com.greate.community.util.CommunityUtil;
import com.greate.community.util.HostHolder;
import com.greate.community.util.RedisKeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * 评论/回复
 */
@Controller
@RequestMapping("/comment")
public class CommentController implements CommunityConstant {

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private CommentService commentService;

    @Autowired
    RBACService rbacService;

    @Autowired
    SectionForbidService sectionForbidService;

    @Autowired
    private DiscussPostService discussPostService;

    @Autowired
    private EventProducer eventProducer;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 添加评论
     * @param discussPostId
     * @param comment
     * @return
     */
    @PostMapping("/add/{discussPostId}")
    public String addComment(@PathVariable("discussPostId") int discussPostId, Comment comment) {
        comment.setUserId(hostHolder.getUser().getId());
        comment.setStatus(0);
        comment.setCreateTime(new Date());
        commentService.addComment(comment);

        // 触发评论事件（系统通知）
        Event event = new Event()
                .setTopic(TOPIC_COMMNET)
                .setUserId(hostHolder.getUser().getId())
                .setEntityType(comment.getEntityType())
                .setEntityId(comment.getEntityId())
                .setData("postId", discussPostId);
        if (comment.getEntityType() == ENTITY_TYPE_POST) {//给帖子评论 通过帖子找到帖子的作者
            DiscussPost target = discussPostService.findDiscussPostById(comment.getEntityId());
            event.setEntityUserId(target.getUserId());
        }
        else if (comment.getEntityType() == ENTITY_TYPE_COMMENT) {//给评论评论  通过评论找作者
            Comment target = commentService.findCommentById(comment.getEntityId());
            event.setEntityUserId(target.getUserId());
        }
        eventProducer.fireEvent(event);

        if (comment.getEntityType() == ENTITY_TYPE_POST) {//给帖子发的话 将其存入es
            // 触发发帖事件，通过消息队列将其存入 Elasticsearch 服务器(其实本系统中只存了帖子 不存评论  所以这条没用 得改)
            event = new Event()
                    .setTopic(TOPIC_PUBLISH)
                    .setUserId(comment.getUserId())
                    .setEntityType(ENTITY_TYPE_POST)
                    .setEntityId(discussPostId);
            eventProducer.fireEvent(event);

            // 计算帖子分数
            String redisKey = RedisKeyUtil.getPostScoreKey();
            redisTemplate.opsForSet().add(redisKey, discussPostId);
        }

        return "redirect:/discuss/detail/" + discussPostId;
    }

    /**
     * 删除评论
     * @param id 评论id
     * @return
     */
    @GetMapping("/deleteMessage")
    @ResponseBody
    public String setDeleteComment(int id, int postId){

        //        通过评论id获得用户id
        int userId= commentService.userIdByCommentId(id);
        boolean jud=false;
        //不是此文章的作者
        if (userId!=hostHolder.getUser().getId()){
            //判断当前帖子所属分区
            Integer i= discussPostService.getSectionByDisscussId(postId);
            //获得此用户的权限
            List<Permission> permissionByUserId = rbacService.getPermissionByUserId(hostHolder.getUser().getId());
            for(Permission permission:permissionByUserId){
                //是管理员或总版主
                if (permission.getPermTag().contains("admin")||permission.getPermTag().contains("kingmoderator")){
                    jud=true;
                }
                //是分区主
                if (permission.getPermTag().equals(i.toString())){
                    jud=true;
                }
            }

        }else {
            //是作者
            jud=true;
        }
        if (jud==false){
            return CommunityUtil.getJSONString(401,"没有该分区权限");
        }




        commentService.updateCommentStatus(1,id);//拉黑

        //更新es服务器  未完成
        return CommunityUtil.getJSONString(0);
    }

}
